#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



import json
import re

import fce_util.libs.localrun as localrun
from fce_util.libs import log as loggers
from fce_util.fceres import fce_res_common

logger = loggers.g_logger.logger

def kube_check(args):
    """
    FCE Ray cluster kube env check
    """
    logger.debug('kube_check enter,args:{}'.format(args))

    kubectl_bin = "kubectl --kubeconfig={}".format(args.conf_path)
    cmd = "{} cluster-info".format(kubectl_bin)
    status, output = localrun.run(cmd)
    if status:
        logger.error("Failed to get kubernetes cluster info")
        fce_res_common(success = False, errcode = 'Deploy.KubeNotFound', errmsg = 'Failed to get kubernetes cluster info')
        return
    
    url_pattern = r'https?://[\d.]+:\d+'
    url_match = re.search(url_pattern, output)
    if url_match:
        cluster_url = url_match.group()
        logger.debug("cluster_url is {}".format(cluster_url))
    else:
        logger.debug("Cluster url not found")
        fce_res_common(success = False, errcode = 'RayCluster.KubeUrlNotFound', errmsg = 'Failed to get kubernetes cluster url')
        return

    cmd = "{} config current-context".format(kubectl_bin)
    status, output = localrun.run(cmd)
    if status:
        logger.error("Failed to get kubernetes cluster id. cmd: %s" % cmd)
        fce_res_common(success = False, errcode = 'RayCluster.KubeIdNotFound', errmsg = 'Failed to get kubernetes cluster id')
        return
    
    try:
        cluster_id = output.split("-")[1].replace('\n', '')
    except Exception as e:
        fce_res_common(success = False, errcode = 'RayCluster.KubeIdNotFound', errmsg = 'Failed to get kubernetes cluster id')
        return

    msg = {'Success': True}
    msg['Message'] = {
        'KubeClusterUrl': cluster_url,
        'KubeClusterId': cluster_id,
    }
    print(json.dumps(msg))

def FCE_kube_check(args):
    if args.deploy == 'kube_check':
        kube_check(args)
        return
    args.this_parser.print_help()

def make(parser):
    """
    FCE Ray Cluster List entry
    """
    parser.add_argument( 
        '--cluster_name',
        dest='cluster_name',
        nargs = '?',
        metavar = ('CLUSTER_NAME'),
        help='Ray Cluster Name',
        required=False,
        )
    
    parser.add_argument( 
        '--cluster_id',
        dest='cluster_id',
        nargs = '?',
        metavar = ('CLUSTER_ID'),
        help='Ray Cluster Id',
        required=False,
        )   
    
    parser.add_argument( 
        '--conf_path',
        dest='conf_path',
        nargs = '?',
        metavar = ('CONF_PATH'),
        help='Kube Config Path',
        required=True,
        )
    
    parser.set_defaults(
        func=FCE_kube_check,
        this_parser=parser
    )
